<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Requests\Api\DemandRequest;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use App\Models\Demand;
use App\Models\User;
use App\Models\Article;
use DB;
use session;

class DemandController extends Controller
{
	// 需求列表页面
	public function demandList(Request $request)
	{
		# 获取页码
        $page = $request->input('page','1');
    	
    	# 获取需求列表
    	if(Cache::has('demand_list'.$page)){
            $demand_list = Cache::get('demand_list'.$page);
        } else {
            $demand_list = Demand::where('is_show',1)->select('xid','title','demand_type','contents','create_time','uid','see_num','comment_num','is_show')->orderBy('xid','desc')->paginate(12);
            Cache::put('demand_list'.$page,$demand_list,3600*24);
        }

		return view('home.Demand.demandList',['demand_list'=>$demand_list]);
	}

	// 需求详情页面
	public function demandDetail($xid)
	{
		# 获取详情
		$detail = Demand::where('xid',$xid)->select('title','demand_type','contents','create_time','uid','see_num','comment_num')->with('headimg')->first();
		# 获取用户信息
		$userinfo = User::where('uid',$detail->uid)->select('username','email')->first();
		# 获取热点文章
		if(Cache::has('hot_article')){
            $hot_article = Cache::get('hot_article');
        } else {
            $hot_article = Article::where('is_show',1)->select('aid','title','created_at','updated_at','cid','author','keywords','click','comment_num','description')->with('category','articlepic')->orderBy('click','desc')->limit(8)->get();
            Cache::put('hot_article',$hot_article,3600*24);
        }
		return view('home.Demand.demandDetail',['userinfo'=>$userinfo,'detail'=>$detail,'hot_article'=>$hot_article]);
	}

	// 发布需求页面
	public function demandRelease()
	{
		# 读取最新发布的
		$demand_list = Demand::where('is_show',1)->select('xid','title','create_time')->orderBy('xid','desc')->limit(5)->get();

		return view('home.Demand.demandRelease',['demand_list'=>$demand_list]);
	}

	// 提交需求
	public function sendDemand(DemandRequest $request)
	{
		$data = $request->all();
        $data['title'] = htmlspecialchars($request->title);
        $data['contents'] = $request->contents;
        $data['create_time'] = time();
        $data['uid'] = session('users.uid');
        $res = Demand::create($data);
        if($res){
        	Cache::delete('demand_list1');
        	return redirect('/home/demandList');
        } else {
        	return redirect('/prompt')->with(['message'=>'添加失败','url' =>'/home/demandList', 'jumpTime'=>3,'status'=>'error']);
        }
	}



}